<?php
/**
 * PHP内置SESSION管理器
 * 
 * 
 * IOC设置项:key/value形式
 * <code>
 *  session_name:会话的名称
 *  session_path:保存路径
 *  session_expire:过期时间
 * </code>
 * @author Leo 2010-10-12 10:59
 *
 */
class PhpSession implements ISession {
	private $session_options;
	public function __construct($session_options = array()) {
		$this->session_options = array_merge ( array ('session_name' => preg_replace ( '/[^\w]/', '_', strtoupper ( WEBSITE ) . '_SID' ), 'session_path' => '', 'session_expire' => 900 ), $session_options );
		$this->start_session ();
	}
	/**
	 * 设置SESSION,当$value=null时从SESSION中删除$name.
	 * @param string $name
	 * @param mixed $value	 
	 */
	public function add($name, $value = null) {
		if (is_null ( $value )) {
			session_unregister ( $name );			
			unset ( $_SESSION [$name] );
		} else {
			$_SESSION [$name] = $value;
		}
	}
	/**
	 * 从SESSION读取数据
	 * @param string $name
	 * @param mixed $default
	 * @return mixed
	 */
	public function get($name, $default = "") {
		if (isset ( $_SESSION [$name] )) {
			return $_SESSION [$name];
		} else {
			return $default;
		}
	}
	//开启会话
	private function start_session() {
		global $__sid;
		if (empty ( $__sid )) {
			@ini_set ( 'session.use_cookies', 1 );
			extract ( $this->session_options );
			
			$__sid = isset ( $_COOKIE [$session_name] ) ? $_COOKIE [$session_name] : null;
			if (! empty ( $__sid )) {
				$this->start_session_step2 ( $session_name, $session_expire, $session_path );
				session_id ( $__sid );
				@session_start ();
			} else {
				$this->start_session_step2 ( $session_name, $session_expire, $session_path );
				@session_start ();
				$__sid = session_id ();
			}
		}
	}
	//第二步
	private function start_session_step2($name, $expire, $path) {
		if (! is_numeric ( $expire )) {
			$expire = 900;
		}
		@session_set_cookie_params ( $expire );
		@session_cache_expire ( $expire );
		if (! empty ( $path ) && is_dir ( $path )) {
			@session_save_path ( $path );
		}
		@session_name ( $name );
	}
}